package com.hp.attendance.serlvet.role;

import com.hp.attendance.entity.Menu;
import com.hp.attendance.entity.dto.RoleMenuDto;
import com.hp.attendance.service.MenuService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/distriRole")
public class RoleDistriServlet extends HttpServlet {
    private MenuService menuService = new MenuService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //预分配菜单
        //查询所有菜单列表 用于分配
        try {
            int roleId = Integer.parseInt(req.getParameter("id"));
            //通过角色id查询已经分配给这个角色的菜单id
            List<Menu> menuList = menuService.getMenusByRoleId(roleId);
            List<Menu> list = menuService.getList();
            List<RoleMenuDto> listRM = new ArrayList<RoleMenuDto>();
            for (Menu menu : list) {
                RoleMenuDto rmd = new RoleMenuDto();
                rmd.setMenu(menu);
                rmd.setRoleId(roleId);
                for (Menu m : menuList) {
                    if(m.getId()==menu.getId()){
                        rmd.setCheck(true);
                    }
                }
               listRM.add(rmd);
            }
            req.setAttribute("roleId",roleId);
            req.setAttribute("list",listRM);
            req.getRequestDispatcher("/pages/role_menu_relation.jsp").forward(req,resp);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
